package com.goldplusgold.tradedelay.app.home.live.utils;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/7/21.
 */

public class MediaUtil {

    static HashMap<String, SoftReference<Bitmap>> cache  = new HashMap<>();
    public interface CallBack{
        void result(Bitmap bitmap);
    }

    public static void getVideoThumbnail(final String url,final CallBack callback) {
        if(cache.containsKey(url)){
            if(callback != null){
                callback.result(cache.get(url).get());
                return;
            }
        }
        final MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        final int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    if (Build.VERSION.SDK_INT >= 14) {
                        retriever.setDataSource(url, new HashMap<String, String>());
                    } else {
                        retriever.setDataSource(url);
                    }
                    bitmap = retriever.getFrameAtTime();
                } catch (IllegalArgumentException ex) {
                    // Assume this is a corrupt video file
                } catch (RuntimeException ex) {
                    // Assume this is a corrupt video file.
                } finally {
                    try {
                        retriever.release();
                    } catch (RuntimeException ex) {
                        // Ignore failures while cleaning up.
                    }
                }
                if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap, bitmap.getWidth(), bitmap.getHeight(),
                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                }
                if(callback != null){
                    callback.result(bitmap);
                    cache.put(url,new SoftReference<Bitmap>(bitmap));
                }
            }
        });
    }

}
